<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { orderDetailByIdService } from '@/api/order'
import { userTypeByIdService } from "@/api/user.js";

// 路由参数
const route = useRoute()

// 订单状态映射
const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已关闭',
    5: '无效订单',
    6: '交易结束，已评价'
}

// 商品信息
const orderItems = ref([])

// 物流信息
const logisticsInfo = ref({})

// 操作记录
const operateHistory = ref([])

// 当前订单状态（用于 el-steps）
const orderStatus = ref(0)

// 订单基础信息
const orderBaseInfo = ref({})

// 用户类型映射（缓存用户类型，避免重复请求）
const userTypeMap = ref({
    0: '系统'
})

// 物流详情
const logisticsDetails = ref([])

// 控制物流详情对话框显示
const showLogisticsDialog = ref(false)

// 切换显隐物流详情
const showLogisticsDetail = () => {
    showLogisticsDialog.value = true
}

// 数据初始化
onMounted(async () => {
    const orderId = route.params.id
    if (!orderId) return

    try {
        const result = await orderDetailByIdService(orderId)
        const data = result.data

        // 设置订单基本信息
        orderBaseInfo.value = data.orderList[0] || {}

        // 设置订单状态（用于 el-steps）
        const currentStatus = data.orderList[0]?.status
        orderStatus.value = currentStatus ? parseInt(currentStatus) : 0

        // 设置商品信息
        orderItems.value = data.orderItemList || []

        // 计算商品小计
        orderItems.value.forEach(item => {
            item.subtotal = (item.productPrice * item.productQuantity).toFixed(2)
        })

        // 设置物流信息
        logisticsInfo.value = data.orderLogisticsList[0] || {}

        // 设置物流详情
        logisticsDetails.value = data.logisticsDetailList || []

        // 设置操作记录
        operateHistory.value = data.orderOperateHistoryList || []

        // 预加载用户类型（可选）
        if (operateHistory.value.length > 0) {
            // 假设操作记录中有 userId 字段
            const userIds = [...new Set(operateHistory.value.map(item => item.operateUser))]
            await Promise.all(userIds.map(id => getUserType(id)))
        }
    } catch (error) {
        console.error('获取订单详情失败:', error)
    }
})

// 获取用户类型
const getUserType = async (id) => {
    // 如果已经缓存过，直接返回
    if (userTypeMap.value[id]) {
        return userTypeMap.value[id]
    }
    try {
        const result = await userTypeByIdService(id)
        userTypeMap.value[id] = result.data.name
        return result.data.name
    } catch (error) {
        console.error('获取用户类型失败:', error)
        return '未知'
    }
}

// 解析规格属性
const parseAttributes = (specs) => {
    try {
        const parsed = JSON.parse(specs)
        return Object.entries(parsed).map(([key, value]) => `${key}: ${value}`).join('; ')
    } catch (e) {
        return specs
    }
}

const formatDateTime = (datetime) => {
    if (!datetime) return '未完成'
    const date = new Date(datetime)
    return date.toLocaleString()
}
</script>



<template>
    <div>
        <!-- 订单状态 -->
        <el-steps :active="orderStatus" align-center>
            <el-step title="提交订单" :description="formatDateTime(orderBaseInfo.createDateTime)"></el-step>
            <el-step title="支付订单" :description="formatDateTime(orderBaseInfo.payTime)"></el-step>
            <el-step title="平台发货" :description="formatDateTime(orderBaseInfo.consignTime)"></el-step>
            <el-step title="确认收货" :description="formatDateTime(orderBaseInfo.endTime)"></el-step>
            <el-step title="完成评价" :description="formatDateTime(orderBaseInfo.commentTime)"></el-step>
        </el-steps>

        <!-- 基本信息 -->
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>基本信息</span>
                    <el-button @click="showLogisticsDetail">订单跟踪</el-button>
                </div>
            </template>
            <el-descriptions :column="6" border>
                <el-descriptions-item label="订单编号">{{ orderBaseInfo.orderNumber }}</el-descriptions-item>
                <el-descriptions-item label="发货单流水号">{{ logisticsInfo.logisticsNumber || '暂无' }}</el-descriptions-item>
                <el-descriptions-item label="用户账号">{{ orderBaseInfo.userId }}</el-descriptions-item>
                <el-descriptions-item label="支付方式">
                    {{ orderBaseInfo.paymentType === 1 ? '支付宝' : orderBaseInfo.paymentType === 2 ? '微信' : '扣减余额' }}
                </el-descriptions-item>
                <el-descriptions-item label="订单来源">{{ orderBaseInfo.sourceType === 1 ? 'APP订单' : '其他' }}</el-descriptions-item>
                <el-descriptions-item label="订单类型">正常订单</el-descriptions-item>
                <el-descriptions-item label="配送方式">{{ logisticsInfo.logisticsCompany || '暂无' }}</el-descriptions-item>
                <el-descriptions-item label="自动确认收货时间">15天</el-descriptions-item>
                <el-descriptions-item label="订单可得优币">0</el-descriptions-item>
                <el-descriptions-item label="订单可得成长值">0</el-descriptions-item>
                <el-descriptions-item label="活动信息">无优惠</el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 收货人信息 -->
        <el-card class="box-card">
            <template #header>
                <div class="card-header"><span>收货人信息</span></div>
            </template>
            <el-descriptions :column="4" border>
                <el-descriptions-item label="收货人">{{ logisticsInfo.contact }}</el-descriptions-item>
                <el-descriptions-item label="手机号码">{{ logisticsInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="邮政编码">518000</el-descriptions-item>
                <el-descriptions-item label="收货地址">{{ logisticsInfo.addressId }}</el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 商品信息 -->
        <el-card class="box-card">
            <template #header>
                <div class="card-header"><span>商品信息</span></div>
            </template>
            <el-table :data="orderItems" border style="width: 100%">
                <el-table-column prop="productPic" label="商品图片" width="100">
                    <template #default="scope">
                        <img :src="scope.row.productPic" alt="Product Image" style="width: 60px; height: 60px;">
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="商品名称"></el-table-column>
                <el-table-column prop="productPrice" label="价格">
                    <template #default="scope">
                        ￥{{ scope.row.productPrice.toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column prop="specs" label="属性">
                    <template #default="scope">
                        {{ parseAttributes(scope.row.specs) }}
                    </template>
                </el-table-column>
                <el-table-column prop="productQuantity" label="数量"></el-table-column>
                <el-table-column prop="subtotal" label="小计">
                    <template #default="scope">
                        ￥{{ scope.row.subtotal }}
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 费用信息 -->
        <el-card class="box-card">
            <template #header>
                <div class="card-header"><span>费用信息</span></div>
            </template>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="商品合计">￥{{ orderBaseInfo.totalPrice?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="运费">￥0</el-descriptions-item>
                <el-descriptions-item label="优惠券">-￥0</el-descriptions-item>
                <el-descriptions-item label="积分抵扣">-￥0</el-descriptions-item>
                <el-descriptions-item label="活动优惠">-￥0</el-descriptions-item>
                <el-descriptions-item label="订单总金额">￥{{ orderBaseInfo.totalPrice?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="应付款金额">￥{{ orderBaseInfo.totalPrice?.toFixed(2) }}</el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 操作信息 -->
        <el-card class="box-card">
            <template #header>
                <div class="card-header"><span>操作信息</span></div>
            </template>
            <el-table :data="operateHistory" border style="width: 100%">
                <el-table-column label="操作者">
                    <template #default="scope">
                        {{ userTypeMap[scope.row.operateUser] || scope.row.operateUser }}
                    </template>
                </el-table-column>
                <el-table-column prop="operateTime" label="操作时间">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.operateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="订单状态">
                    <template #default="scope">
                        {{ statusMap[scope.row.orderStatus] || '未知状态' }}
                    </template>
                </el-table-column>
                <el-table-column prop="note" label="备注"></el-table-column>
            </el-table>
        </el-card>
    </div>

    <!-- 物流详情对话框 -->
    <el-dialog style="width: 25%;" v-model="showLogisticsDialog" title="订单跟踪">
        <el-steps class="el-steps--simple" direction="vertical" :active="logisticsDetails.length - 1" align-center>
            <el-step v-for="(detail, index) in logisticsDetails" :key="index" :title="detail.status"
                :description="formatDateTime(detail.statusTime)">
            </el-step>
        </el-steps>
    </el-dialog>
</template>



<style scoped>
.box-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-steps--simple {
    height: 50vh;
}



</style>